/*
 * @Date: 2022-05-17 21:11:27
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-05-18 10:01:20
 * @FilePath: \react-lvyou\src\store\placeOrder\index.ts
 * @Description: something
 */
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { checkout } from "@/store/shoppingCart";
import axios from "axios";
interface OrderState {
  loading: boolean;
  currentOrder: any;
}
export const fetchPlaceOrder = createAsyncThunk(
  "PlaceOrderSlice/fetchPlaceOrder",
  async (orderId: string, thunkAPI) => {
    const { User } = thunkAPI.getState() as any;
    const { data } = await axios.post(
      `http://123.56.149.216:8089/api/orders/${orderId}/placeOrder`,
      null,
      {
        headers: {
          Authorization: `bearer ${User.token}`,
        },
      },
    );
    return data;
  },
);

const initialState: OrderState = {
  loading: false,
  currentOrder: null,
};

export const PlaceOrderSlice = createSlice({
  name: "PlaceOrderSlice",
  initialState,
  reducers: {},
  extraReducers: {
    // 情况1. 请求开始
    [fetchPlaceOrder.pending.type]: (state) => {
      state.loading = true;
    },
    // 情况2 请求成功
    [fetchPlaceOrder.fulfilled.type]: (state, action) => {
      state.currentOrder = action.payload;
      state.loading = false;
    },
    // 情况3 请求失败
    [fetchPlaceOrder.rejected.type]: (state) => {
      state.loading = false;
    },
    // 情况1. 请求开始
    [checkout.pending.type]: (state) => {
      state.loading = true;
    },
    // 情况2 请求成功
    [checkout.fulfilled.type]: (state, action) => {
      state.currentOrder = action.payload;
      state.loading = false;
    },
    // 情况3 请求失败
    [checkout.rejected.type]: (state) => {
      state.loading = false;
    },
  },
});
